package com.zerui.manager.app.device.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.zerui.cola.dto.Response;
import com.zerui.manager.devciecurfewtimelog.gateway.DeviceCurfewtimeLogGateWay;
import com.zerui.manager.device.Device;
import com.zerui.manager.device.domainservice.DeviceRepository;
import com.zerui.manager.device.gatewayimpl.DeviceGateWayImpl;
import com.zerui.manager.web.cmd.DeviceCurfewTimeCmd;
import com.zerui.manager.web.enums.DeviceAccessStatusEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.Time;
import java.text.ParseException;

/**
 * @author lvfengjun
 * @title: DeviceCurfewTimeCmdExe
 * @description:
 * @date 2023/10/20 16:47
 */
@Component
@CatchAndLog
public class DeviceCurfewTimeCmdExe {

	@Resource
	private DeviceCurfewtimeLogGateWay deviceCurfewtimeLogGateWay;

	@Resource
	private DeviceGateWayImpl deviceGateWay;

	@Resource
	private DeviceRepository deviceRepository;

	/**
	 * 实现设置 设备开始结束时间段
	 *
	 * @param curfewTimeCmd
	 * @return
	 */
	public Response execute(DeviceCurfewTimeCmd curfewTimeCmd) throws ParseException {
		// 日期范围
		Time startTime = curfewTimeCmd.getStartTime();
		Time endTime = curfewTimeCmd.getEndTime();
		int i = endTime.compareTo(startTime);
		if (i == -1 || i == 0) {
			return Response.buildFailure("500", "门禁结束时间不能小于等于开始时间");
		}
		if (this.diffMinute(startTime, endTime) <= 1) {
			return Response.buildFailure("500", "门禁结束时间相差开始时间大于1分钟");
		}
		// 以下将常开常闭任务下发
		Device device = deviceRepository.getByDeviceId(curfewTimeCmd.getDeviceId());
		boolean newFlag = false;
		if (null == device) {
			device = Device.create(curfewTimeCmd.getDeviceId(), 0, 0);
			newFlag = true;
		}
		device.setDeviceId(curfewTimeCmd.getDeviceId());
		device.setStartTime(startTime);
		device.setEndTime(endTime);
		//定时任务默认状态是开启的
		device.setTimedTaskStatus(ObjectUtils.isEmpty(curfewTimeCmd.getTimedTaskStatus()) ?
				DeviceAccessStatusEnum.OPEN.getCode() : curfewTimeCmd.getTimedTaskStatus());

		if (newFlag) {
			// 如果原先没有关联数据，就新增一条关联数据
			deviceRepository.add(device);
		} else {
			//需要先修改 入库的 设备开始结束时间信息  定时任务来实现 定时开关操作
			deviceRepository.updateByDeviceId(device);
		}
		return Response.buildSuccess();
	}

	/**
	 * <p>Title: 相差分钟数</p>
	 * <p>Description: 获取两个java.sql.Time之间的相差分钟</p>
	 *
	 * @param begin 开始的时间
	 * @param end   结束的时间
	 * @return
	 */
	public int diffMinute(Time begin, Time end) {
		long i = begin.getTime();
		long j = end.getTime();
		// next day
		if (i > j) {
			j += 86400000l;
		}
		int d = (int) ((i - j) / 60000l); // 一分钟的毫秒数
		return d = d >= 0 ? d : -d;
	}
}
